Popular Searches
Popular Course Categories
Popular Courses

Introduction to Spring Security Architecture

Introduction to Spring Security Architecture

Spring Security and Secure REST APIs

Introduction to Spring Security Architecture

Course: Advance Java Training

Topic: Introduction to Spring Security Architecture

Course Link: Advance Java Training Course

Demo Link: Register for a Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Spring Security

Spring Security is a security framework for Java and Spring applications. It provides mechanisms for authentication, authorization, protection against common web attacks, session management, and integration with identity providers.

In a Spring Boot application, Spring Security helps ensure that only authenticated users can access protected resources and that users can perform only the operations permitted by their roles or authorities.

For example, an e-commerce application may allow customers to view products and their own orders, while administrators can manage products, update inventory, and view administrative reports.

Spring Security provides configurable security components that work together to process incoming requests and enforce security rules. Its servlet-based architecture primarily uses a chain of filters that runs before the request reaches the Spring MVC controller.

2. Learning Objectives

  • Understand the purpose and architecture of Spring Security.
  • Differentiate authentication from authorization.
  • Understand the role of security filters and filter chains.
  • Learn about SecurityFilterChain, FilterChainProxy, and DelegatingFilterProxy.
  • Understand AuthenticationManager, AuthenticationProvider, and UserDetailsService.
  • Learn how SecurityContext stores the current authentication information.
  • Configure URL-based access rules using modern Spring Security configuration.
  • Understand password encoding, session management, CSRF, and CORS.
  • Explore role-based access control and method-level security.
  • Identify common security configuration mistakes and best practices.

3. Why Is Spring Security Required?

Applications frequently handle sensitive information, including customer profiles, financial records, employee details, and administrative operations. Without proper security controls, unauthorized users may access protected information or execute restricted operations.

Spring Security helps developers implement consistent security policies rather than manually checking credentials and permissions in every controller.

Common Security Requirements

  • Authentication: Verify a user's identity.
  • Authorization: Determine whether the authenticated user may perform an operation.
  • Password security: Store password hashes instead of plaintext passwords.
  • Session management: Manage authenticated user sessions safely.
  • Request protection: Help defend against attacks such as cross-site request forgery.
  • Security headers: Configure browser-facing security protections.
  • Access control: Restrict pages, API endpoints, and business operations.
  • Identity integration: Support mechanisms such as OAuth 2.0 and OpenID Connect when configured.

4. Overview of Spring Security Architecture

In a typical servlet-based Spring Boot application, an HTTP request passes through the servlet container's filter chain. Spring Security integrates into this chain and applies its configured security filters before the request reaches the Spring MVC controller.

Client / Browser
       |
       v
HTTP Request
       |
       v
Servlet Container Filter Chain
       |
       v
DelegatingFilterProxy
       |
       v
FilterChainProxy
       |
       v
Matching SecurityFilterChain
       |
       v
Security Filters
       |
       +---- Authentication
       |
       +---- Security Context
       |
       +---- Authorization
       |
       v
DispatcherServlet
       |
       v
Controller / Service
       |
       v
HTTP Response

This diagram represents a simplified request flow. The exact filters and processing steps depend on the application's configuration, authentication mechanism, and Spring Security version.

5. Major Components of Spring Security

Component Purpose
DelegatingFilterProxy Connects the servlet container's filter mechanism to a Spring-managed filter bean.
FilterChainProxy Acts as the central entry point for Spring Security's servlet filter chains.
SecurityFilterChain Defines which security filters apply to matching HTTP requests.
AuthenticationManager Coordinates authentication processing.
AuthenticationProvider Performs a particular authentication mechanism.
UserDetailsService Loads user information for username-and-password authentication patterns.
PasswordEncoder Encodes passwords and verifies submitted passwords against stored encodings.
SecurityContextHolder Provides access to the current security context.
AuthorizationManager Makes authorization decisions for requests or protected method invocations.

6. Understanding Authentication and Authorization

Authentication and authorization are related but different security concepts.

6.1 Authentication

Authentication verifies who the user is. For example, a user enters a username and password, and the application checks whether those credentials are valid.

Other authentication mechanisms include HTTP Basic authentication, OAuth 2.0 login, OpenID Connect, and token-based authentication.

6.2 Authorization

Authorization determines what an authenticated user is permitted to do. For example, a user may be allowed to view their own profile but not access administrative functions.

Authentication Authorization
Verifies the user's identity. Checks permissions for a resource or operation.
May use passwords, tokens, or identity providers. May use roles, authorities, or custom access rules.
Answers: Who are you? Answers: What are you allowed to do?
Usually occurs before protected-resource authorization. Uses the established authentication and its granted authorities.

7. Understanding DelegatingFilterProxy

DelegatingFilterProxy is a servlet filter that delegates filter processing to a Spring-managed bean. This allows Spring Security to use Spring dependency injection and application configuration while participating in the servlet container's filter chain.

In a typical Spring Boot servlet application, the security infrastructure is automatically configured when the appropriate Spring Security dependency is included. Developers generally do not need to register DelegatingFilterProxy manually.

Its primary role is to bridge the servlet container and Spring's application context.

8. Understanding FilterChainProxy

FilterChainProxy is a central component in Spring Security's servlet architecture. It manages the configured security filter chains and determines which chain should process a request.

It also provides important security infrastructure, including applying the configured HTTP firewall and helping manage security-context cleanup.

An application can define multiple security filter chains. For example, API requests beginning with /api/ can use one security configuration while browser-based application pages use another.

9. Understanding SecurityFilterChain

SecurityFilterChain defines the security filters that should be applied to requests matching a particular request matcher. It is commonly configured using an HttpSecurity object.

Modern Spring Security applications commonly declare one or more SecurityFilterChain beans instead of extending the older WebSecurityConfigurerAdapter class.

Example Security Configuration

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity http) throws Exception {

        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/", "/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(Customizer.withDefaults());

        return http.build();
    }
}

In this example, the home page and URLs under /public/ are accessible without authentication. Other requests require authentication. Form login is enabled using Spring Security's default configuration.

This is a basic learning example. A production application should also consider its CSRF requirements, session policy, password authentication configuration, error handling, and deployment environment.

10. Understanding the Security Filter Chain

A servlet filter can inspect or modify a request or response, perform security checks, or stop processing before a request reaches the application controller.

Spring Security uses several filters for different purposes. Their exact set and order depend on the enabled security features and configuration.

Filter Typical Responsibility
SecurityContextHolderFilter Establishes security-context handling for request processing.
HeaderWriterFilter Writes configured security-related HTTP response headers.
CsrfFilter Applies configured CSRF protection.
UsernamePasswordAuthenticationFilter Processes username-and-password form login requests when form login is enabled.
BasicAuthenticationFilter Processes HTTP Basic credentials when HTTP Basic authentication is enabled.
AnonymousAuthenticationFilter Provides an anonymous authentication representation when appropriate.
ExceptionTranslationFilter Translates certain security exceptions into appropriate HTTP or authentication-entry-point behavior.
AuthorizationFilter Enforces configured request authorization rules.

Not every application uses all these filters. For example, an application configured only for HTTP Basic authentication may not use the username-and-password form login filter.

11. Request Processing Flow

Understanding the request lifecycle helps developers troubleshoot authentication and authorization problems.

  1. The client sends an HTTP request to the application.
  2. The servlet container invokes its configured filters.
  3. Spring Security's filter infrastructure selects a matching SecurityFilterChain.
  4. Security filters apply relevant protections and attempt authentication when required.
  5. Authentication details are made available through the security context.
  6. Authorization rules determine whether the request may proceed.
  7. If access is permitted, the request continues to the Spring MVC dispatcher and controller.
  8. The application generates a response, which passes back through the filter chain.

If authentication fails, the application may return an authentication error or redirect the user to a login page, depending on the configured authentication entry point. If authentication succeeds but authorization fails, Spring Security typically returns an access-denied response for an API or may show an error page for a browser-based application.

12. Understanding AuthenticationManager

AuthenticationManager is the central abstraction responsible for processing authentication requests. Its commonly used implementation, ProviderManager, delegates authentication to one or more configured AuthenticationProvider implementations.

For example, an authentication request may contain a username and password. An appropriate provider checks those credentials using the configured user details service and password encoder.

Conceptual Authentication Flow

Login Request
     |
     v
Authentication Filter
     |
     v
AuthenticationManager
     |
     v
AuthenticationProvider
     |
     v
UserDetailsService
     |
     v
PasswordEncoder Verification
     |
     v
Authentication Result
     |
     v
SecurityContext

This is a simplified flow for username-and-password authentication. Other mechanisms, such as OAuth 2.0 login or JWT-based resource-server authentication, use different components.

13. Understanding AuthenticationProvider

AuthenticationProvider performs authentication for a particular kind of authentication token. An application may use one or several providers depending on its requirements.

For example, a provider can authenticate username-and-password credentials by loading user details and comparing the supplied password with the stored password encoding.

Providers may also integrate with other authentication systems. The selected provider must support the authentication token presented to the authentication manager.

14. Understanding UserDetailsService

UserDetailsService is a common Spring Security interface used to load user details by username. It is frequently used with username-and-password authentication.

The loaded user details may include a username, encoded password, enabled status, account status, and granted authorities.

Example Custom UserDetailsService

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService
        implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        if (!"admin".equals(username)) {
            throw new UsernameNotFoundException(
                "User not found");
        }

        return User.withUsername("admin")
            .password("{noop}change-me")
            .roles("ADMIN")
            .build();
    }
}

Important: The {noop} password prefix disables password hashing for that example. It is shown only to demonstrate the API and must not be used for real user accounts. Production applications should use a suitable password encoder and securely stored credentials, usually backed by a database or identity provider.

15. Understanding PasswordEncoder

PasswordEncoder provides password encoding and verification functionality. Passwords should not be stored in plaintext. Instead, applications should store suitable password hashes and verify submitted passwords against those hashes.

Example Password Encoder Configuration

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class PasswordConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

When registering a user, encode the password before saving it:

String encodedPassword =
        passwordEncoder.encode(rawPassword);

During authentication, Spring Security uses the configured authentication mechanism to compare the submitted password with the stored encoding. Never store plaintext passwords or log credentials.

16. Understanding SecurityContext and SecurityContextHolder

The SecurityContext contains the current authentication information. The SecurityContextHolder provides access to that context during security processing.

The Authentication object commonly contains:

  • The authenticated principal, which represents the current user or identity.
  • The credentials used for authentication, which are commonly cleared after authentication when appropriate.
  • The granted authorities associated with the identity.
  • The authentication state.

Accessing the Current User

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

Authentication authentication =
    SecurityContextHolder.getContext().getAuthentication();

String username = authentication.getName();

This example retrieves the current authentication name when one is available. Code that depends on authentication should handle anonymous or unauthenticated requests appropriately.

In servlet applications, Spring Security normally associates the context with request processing and manages its cleanup. Avoid manually storing authentication information in static fields or application-wide variables.

17. Understanding Roles and Authorities

Authorities represent permissions granted to an authenticated principal. A role is commonly represented as an authority following a naming convention.

Spring Security's role-based helpers typically apply the ROLE_ prefix. For example, hasRole("ADMIN") normally checks for the authority ROLE_ADMIN, while hasAuthority("REPORT_READ") checks for that exact authority string.

Role or Authority Example Access
ROLE_USER Access regular user features.
ROLE_ADMIN Access administrative features.
REPORT_READ Read reports if the exact authority is granted.
ORDER_WRITE Perform operations requiring order-writing permission.

18. Configuring URL-Based Authorization

Spring Security lets developers define authorization rules for HTTP requests. Rules should be explicit and ordered so that specific patterns are evaluated before broader patterns.

Example Role-Based Configuration

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(
            HttpSecurity http) throws Exception {

        http
            .authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/", "/login", "/css/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
                .anyRequest().authenticated()
            )
            .formLogin(Customizer.withDefaults());

        return http.build();
    }
}

In this example:

  • The home page, login page, and CSS resources are public.
  • URLs under /admin/ require the administrator role.
  • URLs under /user/ require either the user or administrator role.
  • Other requests require authentication.

Make sure your authentication setup actually grants the expected roles. Public access should be limited to resources intended to be public.

19. Method-Level Security

Method-level security protects service methods or other Spring-managed methods based on the current user's authorities. It is useful when access rules should apply regardless of which controller invokes the business operation.

Enable Method Security

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;

@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig {
}

Protect a Method

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

@Service
public class ReportService {

    @PreAuthorize("hasRole('ADMIN')")
    public String generateAdminReport() {
        return "Administrative report generated";
    }

    @PreAuthorize("hasAuthority('REPORT_READ')")
    public String readReport() {
        return "Report data";
    }
}

@PreAuthorize checks the access expression before the method executes. Method security relies on Spring's method interception, so calls must pass through the relevant Spring proxy for the security advice to apply.

20. Understanding CSRF Protection

Cross-Site Request Forgery (CSRF) is an attack in which a browser can be induced to submit an unwanted request to a website where the user is already authenticated.

Spring Security includes CSRF protection for applicable servlet-based configurations. It is especially important for browser applications that authenticate users through cookies or sessions.

Important CSRF Practices

  • Keep CSRF protection enabled for session-based browser applications unless there is a well-understood reason for a different design.
  • Include the expected CSRF token in state-changing requests when required.
  • Do not assume that an API is safe from CSRF merely because it uses JSON.
  • Review the authentication mechanism, cookie behavior, and client architecture before configuring exclusions.

Some stateless APIs using bearer tokens supplied explicitly in an authorization header may have different CSRF considerations. Disabling CSRF without analyzing the actual authentication and browser behavior can create vulnerabilities.

21. Understanding CORS

Cross-Origin Resource Sharing (CORS) is a browser security mechanism that controls whether a web page from one origin may access resources from another origin.

For example, a React frontend served from one origin may need to call a Spring Boot API hosted on a different origin.

Example CORS Configuration

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsConfig {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();

        configuration.setAllowedOrigins(
            List.of("https://frontend.example.com"));
        configuration.setAllowedMethods(
            List.of("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowedHeaders(
            List.of("Authorization", "Content-Type"));
        configuration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source =
            new UrlBasedCorsConfigurationSource();

        source.registerCorsConfiguration("/api/**", configuration);
        return source;
    }
}

Enable CORS support in the relevant security configuration with http.cors(Customizer.withDefaults()) when appropriate. Replace the example origin with the actual trusted frontend origin.

When credentials are allowed, configure explicit trusted origins rather than using a wildcard origin. CORS is not an authentication mechanism and does not replace authorization checks.

22. Session Management

Session management controls how authenticated sessions are created, maintained, and invalidated. Spring Security supports session-related protections and configuration for servlet applications.

Common session-management considerations include:

  • Use HTTPS in production to protect session cookies in transit.
  • Use appropriate cookie attributes, such as Secure, HttpOnly, and a suitable SameSite policy.
  • Configure session fixation protection appropriately.
  • Provide a logout mechanism that invalidates the session where required.
  • Choose session creation policies based on the application's authentication design.
  • Set sensible session timeout and reauthentication policies for sensitive operations.

Example Stateless Session Policy

import org.springframework.security.config.http.SessionCreationPolicy;

http.sessionManagement(session -> session
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);

This configuration is commonly used for APIs that do not use an HTTP session to maintain authentication state. A stateless policy does not automatically validate tokens; the application must still configure an appropriate authentication mechanism, such as a resource server.

23. HTTP Basic Authentication and Form Login

Spring Security supports different ways to authenticate users.

HTTP Basic Authentication

HTTP Basic sends credentials using the HTTP Authorization header. It should be used only over HTTPS in real deployments because the credentials are encoded, not encrypted, by the Basic scheme itself.

http.httpBasic(Customizer.withDefaults());

Form Login

Form login allows users to submit credentials through a login page. Spring Security can provide a default login page or integrate with a custom login page.

http.formLogin(Customizer.withDefaults());

Choose an authentication mechanism based on the client type and application architecture. Browser-based applications and machine-to-machine APIs may require different configurations.

24. Understanding OAuth 2.0 and OpenID Connect

OAuth 2.0 is an authorization framework used to grant limited access to protected resources. OpenID Connect (OIDC) builds on OAuth 2.0 and adds an identity layer for authenticating users.

Spring Security supports OAuth 2.0 client login, resource-server authentication, and related capabilities when configured with the appropriate dependencies and identity provider settings.

  • OAuth 2.0 Client: Allows an application to obtain authorization and access tokens from an authorization server.
  • OIDC Login: Allows users to sign in through an identity provider.
  • Resource Server: Protects APIs by validating supported bearer tokens, commonly JWTs or opaque tokens.

For production systems, validate token signatures or introspection responses, issuer, audience where applicable, expiration, and required scopes or authorities according to the chosen token format and security design.

25. Custom Security Filters

Sometimes an application needs a custom filter to perform a specialized operation, such as extracting a tenant identifier or processing a custom authentication token.

Spring Security's HttpSecurity API supports adding filters before, after, or at a particular filter position. Custom filters should be placed according to the authentication and security-context information they require.

Example Filter Registration

http.addFilterBefore(
    customFilter,
    org.springframework.security.web.authentication
        .UsernamePasswordAuthenticationFilter.class
);

This is a conceptual registration example; customFilter must be an appropriately implemented filter. The correct position depends on the filter's purpose. Do not copy an arbitrary position without understanding the surrounding filter behavior.

If a custom filter is also registered directly with the servlet container as a Spring bean, it may run twice or at an unexpected point. Review servlet filter registration when adding custom Spring Security filters.

26. Handling Authentication and Access-Denied Errors

Authentication and authorization failures should be handled clearly without exposing sensitive information.

HTTP Status Typical Meaning Example
200 OK The request completed successfully. An authorized user retrieves a report.
401 Unauthorized Authentication is missing or invalid for the requested resource. An API request lacks valid credentials.
403 Forbidden The request is understood, but access is denied. An authenticated user lacks the required authority.
302 Found A redirect may be used in browser-based login flows. An unauthenticated browser user is redirected to a login page.

The precise response depends on the configured authentication entry point, access-denied handler, client type, and security rules. API clients generally benefit from consistent HTTP error responses, while browser applications may use redirects and login pages.

27. Spring Security Dependencies

For a typical Spring Boot servlet application, Spring Security can be added through the security starter.

Maven Dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Use the Spring Boot dependency management provided by your project rather than manually selecting unrelated Spring Security versions. Adding the starter activates Spring Boot's security auto-configuration unless the application overrides it.

28. Common Spring Security Problems and Solutions

Problem Possible Cause Solution
All pages require login Authorization rules require authentication for every request. Explicitly permit only the intended public routes.
Admin page returns 403 The current user lacks the required role or authority. Check the granted authorities and the authorization expression.
Login always fails Incorrect credentials, password encoding, or user lookup logic. Verify the user store, password encoder, and authentication provider.
CSRF error on form submission The required CSRF token is missing or invalid. Include the token correctly and verify the CSRF configuration.
CORS error in the browser The frontend origin or request settings are not permitted. Configure trusted origins, methods, headers, and credentials as needed.
Custom filter runs twice The filter is registered with both the servlet container and Spring Security. Review filter registration and disable duplicate servlet registration if appropriate.
Method security has no effect The method call bypasses the Spring proxy or method security is not enabled. Enable method security and ensure calls pass through the relevant proxy.
Unexpected redirect for API calls Browser-oriented form login behavior is being used for an API. Configure an API-appropriate authentication entry point and response handling.

29. Spring Security Best Practices

  • Use a supported Spring Boot and Spring Security version and follow its official documentation.
  • Require HTTPS for production authentication and sensitive data.
  • Store password hashes using a suitable password encoder.
  • Apply least-privilege authorization and deny access by default where appropriate.
  • Keep CSRF protection enabled for browser-based session authentication unless a justified design requires otherwise.
  • Configure CORS with explicit trusted origins.
  • Use short-lived tokens and appropriate validation policies for token-based APIs.
  • Protect administrative endpoints and sensitive service methods.
  • Avoid logging passwords, access tokens, session identifiers, or other sensitive credentials.
  • Keep security dependencies updated and review security advisories.
  • Write automated tests for public routes, authenticated routes, role restrictions, and authentication failures.
  • Use security debugging and logs carefully, avoiding disclosure of secrets in production.

30. Practical Project: Secure Student Management System

Build a Spring Boot application that protects student records using Spring Security.

Project Requirements

  1. Create a Spring Boot project with Spring Web and Spring Security dependencies.
  2. Create student endpoints for viewing and managing student records.
  3. Configure a public endpoint for basic application information.
  4. Require authentication to access student information.
  5. Allow users with the ROLE_ADMIN role to create, update, or delete student records.
  6. Use a suitable password encoder for stored credentials.
  7. Configure CSRF protection according to the application's client and authentication model.
  8. Test successful login, invalid credentials, forbidden access, and permitted requests.
  9. Add integration tests for the configured authorization rules.

Example Controller

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudentController {

    @GetMapping("/public/info")
    public String publicInfo() {
        return "Public student information";
    }

    @GetMapping("/student/profile")
    public String studentProfile() {
        return "Protected student profile";
    }

    @GetMapping("/admin/dashboard")
    public String adminDashboard() {
        return "Administrative dashboard";
    }
}

Combine this controller with the URL-based authorization configuration described earlier. The public information endpoint can be accessible without login, the profile endpoint can require authentication, and the dashboard can require an administrator role.

For a complete project, replace demonstration users with a secure user store and ensure that the service layer also protects sensitive business operations.

31. Interview Questions and Answers

Q1. What is Spring Security?

Spring Security is a framework that provides authentication, authorization, and protection against common security attacks for Spring applications.

Q2. What is the difference between authentication and authorization?

Authentication verifies identity, while authorization determines whether that identity has permission to access a resource or perform an operation.

Q3. What is DelegatingFilterProxy?

It connects the servlet container's filter mechanism to a filter managed by Spring's application context.

Q4. What is FilterChainProxy?

It is the central Spring Security servlet filter that selects and invokes the matching security filter chain.

Q5. What is SecurityFilterChain?

It defines the security filters applied to requests that match its configured request matcher.

Q6. What is AuthenticationManager?

It is the main abstraction for processing authentication requests and commonly delegates to configured authentication providers.

Q7. What is UserDetailsService?

It loads user details by username for authentication mechanisms that use Spring Security's user-details model.

Q8. What is SecurityContextHolder?

It provides access to the security context associated with the current security-processing context.

Q9. What is PasswordEncoder?

It provides password encoding and matching functionality so that applications do not need to store plaintext passwords.

Q10. What is CSRF protection?

It helps protect applications against forged requests, particularly in browser-based applications that rely on automatically sent credentials such as session cookies.

Q11. What is the difference between hasRole and hasAuthority?

hasRole("ADMIN") normally checks for ROLE_ADMIN, while hasAuthority("REPORT_READ") checks the exact authority string supplied.

Q12. What is method-level security?

It applies authorization rules to method invocations, often using annotations such as @PreAuthorize.

Q13. What is the difference between 401 and 403?

A 401 response usually indicates that valid authentication is missing or has failed. A 403 response usually indicates that access is denied, often because the authenticated user lacks permission.

Q14. Why should CSRF not be disabled blindly?

Disabling CSRF without considering the authentication mechanism and browser behavior can expose an application to forged state-changing requests.

32. Quick Revision Checklist

  • Spring Security provides authentication, authorization, and web security protections.
  • Authentication verifies identity; authorization checks permissions.
  • DelegatingFilterProxy connects servlet filtering with Spring-managed components.
  • FilterChainProxy selects the appropriate SecurityFilterChain.
  • Security filters execute in a configured order.
  • AuthenticationManager coordinates authentication providers.
  • UserDetailsService commonly loads username-based user information.
  • PasswordEncoder supports secure password storage and verification.
  • SecurityContextHolder provides access to the current security context.
  • Use roles and authorities to enforce access-control rules.
  • Use method-level security for sensitive business operations when appropriate.
  • Understand CSRF, CORS, session management, and authentication entry points.
  • Use HTTPS, least privilege, secure credentials, and automated security tests.

33. Conclusion

Spring Security architecture provides a structured approach to securing Java and Spring Boot applications. Its servlet filter infrastructure processes incoming requests, authentication components verify identities, and authorization components determine whether users can access protected resources.

Understanding SecurityFilterChain, FilterChainProxy, AuthenticationManager, SecurityContextHolder, and authorization rules helps developers design maintainable and secure applications. By combining clear access policies with secure password handling, suitable CSRF and CORS configuration, session protections, and comprehensive testing, developers can build applications that better protect users and business data.

Continue Learning: Explore the Advance Java Training course at JustAcademy.

Course Demo: Register for a JustAcademy course demo.

Official Documentation: Spring Security Architecture Documentation.

Additional Resource: Visit the JustAcademy Official Website.

Previous Next
whatsapp